package com.example.mp.modular.system.handler.EventsHandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mp.core.common.LogUtil;
import com.example.mp.modular.system.dao.SysUserWechatMapper;
import com.example.mp.modular.system.handler.AbstractHandler;
import com.example.mp.modular.system.model.SysUserWechat;
import com.example.mp.modular.system.service.ISysUserWechatService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class UnsubscribeHandler extends AbstractHandler {

    @Autowired
    private ISysUserWechatService wechatService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
        this.logger.info("取消关注用户 OPENID: " + openId);

        try {
            boolean isSuccess = wechatService.remove(new QueryWrapper<SysUserWechat>().lambda().eq(SysUserWechat::getOpenid, wxMessage.getFromUser()));
            LogUtil.info("删除订阅用户信息成功！");
        } catch (Exception x) {
            LogUtil.error("取消订阅事件删除用户信息异常", x);
        }


        return null;
    }

}
